﻿using System;
using System.IO;
using System.Web;

namespace MikeKappel.Com.CS.HttpModules
{
    public class StreamFilter : Stream
    {
        #region Interfaces
            public interface IFilterer
            {
                String Filter(String unfiltered);
            }
        #endregion
        #region Variables
            private Stream sink;
        #endregion
        #region Properites
            private IFilterer Filterer { get; set; }
            public override long Position { get; set; }
            public override bool CanRead
            {
                get { return true; }
            }
            public override bool CanSeek
            {
                get { return true; }
            }
            public override bool CanWrite
            {
                get { return true; }
            }
            public override void Flush()
            {
                sink.Flush();
            }
            public override long Length
            {
                get { return 0; }
            }
        #endregion
        #region Constructors
            /// <summary>
            /// 
            /// </summary>
            /// <param name="sink"></param>
            /// <param name="filterer"></param>
            public StreamFilter(Stream sink, IFilterer filterer)
            {
                this.Filterer = filterer;
                this.sink = sink;
            }
        #endregion
        #region Methods
            public override int Read(byte[] buffer, int offset, int count)
            {
                return sink.Read(buffer, offset, count);
            }
            public override long Seek(long offset, SeekOrigin origin)
            {
                return sink.Seek(offset, origin);
            }
            public override void SetLength(long value)
            {
                sink.SetLength(value);
            }
            public override void Close()
            {
                sink.Close();
            }
            public override void Write(byte[] buffer, int offset, int count)
            {
                byte[] data = new byte[count];
                Buffer.BlockCopy(buffer, offset, data, 0, count);
                string html = System.Text.Encoding.Default.GetString(buffer);

                byte[] outdata = System.Text.Encoding.Default.GetBytes(this.Filterer.Filter(html));
                sink.Write(outdata, 0, outdata.GetLength(0));
            }
        #endregion
    }
}
